<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class Image {
    public $id;
    public $bretId;
    public $imageUrl;
    public $index;
    public $dateCreated;
    
    public function __construct() {
        //allocate your stuff
    }
    
    public static function withId($id) {
        $instance = new self();
        $db = Database::getInstance();
        $result = $db->query("SELECT * FROM images WHERE id = '$id'");
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $row = $result->dataTable->rows[0];
                $instance->id = $row["id"];
                $instance->bretId = $row["bretid"];
                $instance->imageUrl = $row["imageurl"];
                $instance->index = $row["index"];
                $instance->dateCreated = $row["datecreated"];
                return $instance;
            } else {
                $controller = new ErrorController(new Error(), new ErrorView(), "404", "Not found any image with provided id");
                $controller->returnError();
                return NULL;
            }
        } else {
            $controller = new ErrorController(new Error(), new ErrorView, $result->returnCode, $result->message);
            $controller->returnError();
            return NULL;
        }
    }
    
    public static function withBretId($id) {
        global $absoluteUrl;
        $images = array();
        $db = Database::getInstance();
        $result = $db->query("SELECT * FROM images WHERE bretid = '$id' ORDER BY  `images`.`index` ASC ");
        //echo "SELECT * FROM images WHERE bretid = '$id' ORDER BY  `images`.`index` ASC";
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow > 0) {
                foreach($result->dataTable->rows as $row) {
                    $instance = new self();
                    $instance->id = $row["id"];
                    $instance->bretId = $row["bretid"];
                    $instance->imageUrl = $absoluteUrl.'/Images/brets/'.$row["bretid"].'/'.$row["imageurl"];
                    $instance->index = $row["index"];
                    $instance->dateCreated = $row["datecreated"];
                    $images[] = $instance;
                }
            } else {
                $controller = new ErrorController(new Error(), new ErrorView(), "404", "Not found any image with provided id");
                $controller->returnError();
                return NULL;
            }
        } else {
            $controller = new ErrorController(new Error(), new ErrorView, $result->returnCode, $result->message);
            $controller->returnError();
            return NULL;
        }
        return $images;
    }
}